//
//  BDMyFriendViewController.m
//  iOS_beboy
//
//  Created by Chuz NetTech on 17/10/20.
//  Copyright © 2017年 com.8xiong. All rights reserved.
//

#import "BDMyFriendViewController.h"
#import "BDUserModel.h"
#import "BDMyDongTai.h"
#import "BDMyfriendTableViewCell.h"
#import <YYKit.h>
#import <YYTextLayout.h>
#import "BDPostHelper.h"
#import "BDTextLinePositionModifier.h"
#import "BDMyFriendViewController.h"

@interface BDMyFriendViewController ()<UITableViewDelegate,UITableViewDataSource,UIScrollViewDelegate>
@property (nonatomic, strong) UITableView *tableView;
@property (nonatomic, strong) UIView *topView;
@property (nonatomic, strong) UIView *customNavi;
@property (nonatomic, strong) NSMutableArray *datasourceArray;
@property (nonatomic, strong) NSString *starPage;
@property (nonatomic, strong) NSString *starSize;

@end

@implementation BDMyFriendViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    self.title = ASLocalizedString(@"朋友圈动态");
    
    self.starPage = @"1";
    self.starSize = @"10";
    
    [self createUI];
    
    self.datasourceArray = [NSMutableArray array];
    
    self.tableView.mj_header = [MJRefreshNormalHeader headerWithRefreshingBlock:^{
        self.starPage = @"1";
        [self.datasourceArray removeAllObjects];
        [self requestData];
    }];
    [self.tableView.mj_header beginRefreshing];
    if (@available(iOS 11.0, *)) {
        self.tableView.contentInsetAdjustmentBehavior = UIScrollViewContentInsetAdjustmentNever;
    } else {
        // Fallback on earlier versions
    }
}

-(void)createUI{
    BDUserModel *user = [BDUserModel getCurrentUser];
    
    self.topView = [[UIView alloc] init];
    _topView.left = 0;
    _topView.top = 0;
    _topView.size = CGSizeMake(kBDScreenWidth, 175);
    _topView.backgroundColor = [UIColor clearColor];
    
    UIImageView *bigImage = [[UIImageView alloc] initWithFrame:CGRectMake(0, 0, kBDScreenWidth, 175)];
    [bigImage sd_setImageWithURL:[NSURL URLWithString:user.cover] placeholderImage:[UIImage imageNamed:@"user_top"]];
    bigImage.contentMode = UIViewContentModeScaleAspectFill;
    bigImage.clipsToBounds = YES;
    [_topView addSubview:bigImage];
    
    
    UIView *blackView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, kBDScreenWidth, 175)];
    blackView.backgroundColor = [UIColor blackColor];
    blackView.alpha = 0.4;
    [_topView addSubview:blackView];
    
    [self.view addSubview:self.topView];
    
    
    self.customNavi = [[UIView alloc] initWithFrame:CGRectMake(0, 0, kBDScreenWidth, kBDTopHeight)];
    _customNavi.backgroundColor = [UIColor colorWithRed:54/255.0 green:54/255.0 blue:54/255.0 alpha:1.0f];
    _customNavi.alpha = 0;
    [self.view addSubview:_customNavi];
    
    UIButton *backButton = [[UIButton alloc]initWithFrame:CGRectMake(0, 0, 30, 30)];
    backButton.centerY = 42;
    [backButton setImage:[UIImage imageNamed:@"back"] forState:UIControlStateNormal];
    [self.view addSubview:backButton];
    
    [[backButton rac_signalForControlEvents:UIControlEventTouchUpInside] subscribeNext:^(__kindof UIControl * _Nullable x) {
        [self.navigationController popViewControllerAnimated:YES];
    }];
    
    UILabel *titleLabel = [[UILabel alloc] init];
    titleLabel.textColor = [UIColor whiteColor];
    titleLabel.text = ASLocalizedString(@"朋友圈动态");
    titleLabel.font = [UIFont systemFontOfSize:17];
    [titleLabel sizeToFit];
    titleLabel.left = (kBDScreenWidth - titleLabel.width) / 2;
    titleLabel.centerY = 42;
    [self.view addSubview:titleLabel];
    
    
}

-(UITableView *)tableView{
    if (!_tableView) {
        self.tableView = [[UITableView alloc] init];
        _tableView.left = 0;
        _tableView.top = 0;
        _tableView.size = CGSizeMake(kBDScreenWidth, kBDScreenHeight);
        _tableView.contentInset = UIEdgeInsetsMake(175, 0, 0, 0);
        _tableView.delegate = self;
        _tableView.dataSource = self;
        //_tableView.separatorColor = [UIColor clearColor];
        _tableView.tableFooterView = [[UIView alloc]initWithFrame:CGRectZero];
//        _tableView.backgroundColor = [UIColor colorWithHexString:@"deedff"];
        _tableView.backgroundColor = [UIColor whiteColor];
        [_tableView registerClass:[BDMyfriendTableViewCell class] forCellReuseIdentifier:@"friendCELL"];
        [self.view insertSubview:self.tableView atIndex:0];
    }
    return _tableView;
}

-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return self.datasourceArray.count;
}

-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    BDMyfriendTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"friendCELL" forIndexPath:indexPath];
    
    cell.selectionStyle = UITableViewCellEditingStyleNone;
    cell.backgroundColor = [UIColor clearColor];
    BDMyDongTai *model = self.datasourceArray[indexPath.row];
    
    [cell configData:model];
    
    return cell;
}

-(CGFloat )tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    BDMyDongTai *model = self.datasourceArray[indexPath.row];
    return model.cellHeight;
}

-(void)requestData{
    
    NSString *url = [NSString stringWithFormat:@"%@circles?page=%@&size=%@",KBDBaseURL,self.starPage,self.starSize];
    NSString *headValid = [BDUserModel getHeaderValidation];
    
    RACSignal *signal = [[BDNetworkingServer yy_GET:url parameters:nil validation:headValid automaticProcessingError:YES] execute:nil];
    [signal subscribeNext:^(id  _Nullable x) {
        NSMutableArray *dataArr = [BDMyDongTai mj_objectArrayWithKeyValuesArray:x[@"list"]];
        NSMutableArray *dateArr = [NSMutableArray array];
        for (int i = 0; i < dataArr.count; i++) {
            BDMyDongTai *model = dataArr[i];
            NSDate *curDate = [NSDate dateWithTimeIntervalSince1970:model.created_at.floatValue];
            NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
            [formatter setDateFormat:@"MM-dd"];
            NSString *dateStr = [formatter stringFromDate:curDate];
            if ([dateArr containsObject:dateStr]) {
                model.needDisplayDate = NO;
            }else{
                model.needDisplayDate = YES;
                [dateArr addObject:dateStr];
            }
            
            NSMutableAttributedString *text = [self _textWithPost:model.content
                                                         fontSize:12
                                                        textColor:[UIColor colorWithHexString:@"666666"]];
            if (text.length == 0) return;
            BDTextLinePositionModifier *modifier = [BDTextLinePositionModifier new];
            modifier.font = [UIFont fontWithName:@"Heiti SC" size:12];
            modifier.paddingTop = 10;
            modifier.paddingBottom = 0;
            
            YYTextContainer *container = [YYTextContainer new];
            container.size = CGSizeMake(kBDScreenWidth - 40, MAXFLOAT);
            container.linePositionModifier = modifier;
            
            YYTextLayout *layout = [YYTextLayout layoutWithContainer:container text:text];
            if (!layout) return;
            
            CGFloat textHeight = [modifier heightForLineCount:layout.rowCount];
            
            if (model.images.count == 0) {
                model.cellHeight = 20 + textHeight + 40 + 10 + 10;
            }else if (model.images.count <= 3 && model.images.count > 0) {
                model.cellHeight = 20 + textHeight + 40 + 10 + (kBDScreenWidth - 80) / 3 + 10 + 10;
            }else if (model.images.count > 3 && model.images.count <= 6){
                model.cellHeight = 20 + textHeight + 40 + (10 + (kBDScreenWidth - 80) / 3) * 2 + 10 + 10;
            }else if (model.images.count > 6){
                model.cellHeight = 20 + textHeight + 40 + (10 + (kBDScreenWidth - 80) / 3) * 3 + 10 + 10;
            }
        }
        [self.datasourceArray addObjectsFromArray:dataArr];
        self.isEnd = [x[@"is_end"] boolValue];
        self.starPage = x[@"next_page"];
        [self.tableView.mj_header endRefreshing];
        [self.tableView.mj_footer endRefreshing];
        self.tableView.mj_footer = [MJRefreshBackNormalFooter footerWithRefreshingBlock:^{
            [self requestData];
        }];
        
        [self setTableiewFooterViewStateFor:self.tableView datasourceCount:self.datasourceArray.count];
        [self.tableView reloadData];
        self.tableView.mj_header = nil;
        
    }];
}

- (void)scrollViewDidScroll:(UIScrollView *)scrollView{
    self.topView.bottom = -self.tableView.contentOffset.y;
    self.topView.bottom = self.topView.bottom < 0 ? 0 : self.topView.bottom;
    self.topView.top = self.topView.top > 0 ? 0 : self.topView.top;
    CGFloat offset = scrollView.contentOffset.y;
    CGFloat alpha = 1 + (offset + kBDTopHeight) / 1.0 / (self.topView.height - kBDTopHeight);
    alpha = alpha > 1 ? 1 : alpha;
    alpha = alpha < 0 ? 0 : alpha;
    self.customNavi.alpha = alpha;
}

///对文本的处理
- (NSMutableAttributedString *)_textWithPost:(NSString *)contextString
                                    fontSize:(CGFloat)fontSize
                                   textColor:(UIColor *)textColor {
    if (!contextString) return nil;
    
    NSMutableString *string = contextString.mutableCopy;
    if (string.length == 0) return nil;
    
    // 字体
    UIFont *font = [UIFont systemFontOfSize:fontSize];
    // 高亮状态的背景
    YYTextBorder *highlightBorder = [YYTextBorder new];
    highlightBorder.insets = UIEdgeInsetsMake(-2, 0, -2, 0);
    highlightBorder.cornerRadius = 3;
    
    
    NSMutableAttributedString *text = [[NSMutableAttributedString alloc] initWithString:string];
    text.font = font;
    text.color = textColor;
    
    //    // 根据 urlStruct 中每个 URL.shortURL 来匹配文本，将其替换为图标+友好描述
    //    for (WBURL *wburl in status.urlStruct) {
    //        if (wburl.shortURL.length == 0) continue;
    //        if (wburl.urlTitle.length == 0) continue;
    //        NSString *urlTitle = wburl.urlTitle;
    //        if (urlTitle.length > 27) {
    //            urlTitle = [[urlTitle substringToIndex:27] stringByAppendingString:YYTextTruncationToken];
    //        }
    //        NSRange searchRange = NSMakeRange(0, text.string.length);
    //        do {
    //            NSRange range = [text.string rangeOfString:wburl.shortURL options:kNilOptions range:searchRange];
    //            if (range.location == NSNotFound) break;
    //
    //            if (range.location + range.length == text.length) {
    //                if (status.pageInfo.pageID && wburl.pageID &&
    //                    [wburl.pageID isEqualToString:status.pageInfo.pageID]) {
    //                    if ((!isRetweet && !status.retweetedStatus) || isRetweet) {
    //                        if (status.pics.count == 0) {
    //                            [text replaceCharactersInRange:range withString:@""];
    //                            break; // cut the tail, show with card
    //                        }
    //                    }
    //                }
    //            }
    //
    //            if ([text attribute:YYTextHighlightAttributeName atIndex:range.location] == nil) {
    //
    //                // 替换的内容
    //                NSMutableAttributedString *replace = [[NSMutableAttributedString alloc] initWithString:urlTitle];
    //                if (wburl.urlTypePic.length) {
    //                    // 链接头部有个图片附件 (要从网络获取)
    //                    NSURL *picURL = [WBStatusHelper defaultURLForImageURL:wburl.urlTypePic];
    //                    UIImage *image = [[YYImageCache sharedCache] getImageForKey:picURL.absoluteString];
    //                    NSAttributedString *pic = (image && !wburl.pics.count) ? [self _attachmentWithFontSize:fontSize image:image shrink:YES] : [self _attachmentWithFontSize:fontSize imageURL:wburl.urlTypePic shrink:YES];
    //                    [replace insertAttributedString:pic atIndex:0];
    //                }
    //                replace.font = font;
    //                replace.color = kWBCellTextHighlightColor;
    //
    //                // 高亮状态
    //                YYTextHighlight *highlight = [YYTextHighlight new];
    //                [highlight setBackgroundBorder:highlightBorder];
    //                // 数据信息，用于稍后用户点击
    //                highlight.userInfo = @{kWBLinkURLName : wburl};
    //                [replace setTextHighlight:highlight range:NSMakeRange(0, replace.length)];
    //
    //                // 添加被替换的原始字符串，用于复制
    //                YYTextBackedString *backed = [YYTextBackedString stringWithString:[text.string substringWithRange:range]];
    //                [replace setTextBackedString:backed range:NSMakeRange(0, replace.length)];
    //
    //                // 替换
    //                [text replaceCharactersInRange:range withAttributedString:replace];
    //
    //                searchRange.location = searchRange.location + (replace.length ? replace.length : 1);
    //                if (searchRange.location + 1 >= text.length) break;
    //                searchRange.length = text.length - searchRange.location;
    //            } else {
    //                searchRange.location = searchRange.location + (searchRange.length ? searchRange.length : 1);
    //                if (searchRange.location + 1>= text.length) break;
    //                searchRange.length = text.length - searchRange.location;
    //            }
    //        } while (1);
    //    }
    //
    //    // 根据 topicStruct 中每个 Topic.topicTitle 来匹配文本，标记为话题
    //    for (WBTopic *topic in status.topicStruct) {
    //        if (topic.topicTitle.length == 0) continue;
    //        NSString *topicTitle = [NSString stringWithFormat:@"#%@#",topic.topicTitle];
    //        NSRange searchRange = NSMakeRange(0, text.string.length);
    //        do {
    //            NSRange range = [text.string rangeOfString:topicTitle options:kNilOptions range:searchRange];
    //            if (range.location == NSNotFound) break;
    //
    //            if ([text attribute:YYTextHighlightAttributeName atIndex:range.location] == nil) {
    //                [text setColor:kWBCellTextHighlightColor range:range];
    //
    //                // 高亮状态
    //                YYTextHighlight *highlight = [YYTextHighlight new];
    //                [highlight setBackgroundBorder:highlightBorder];
    //                // 数据信息，用于稍后用户点击
    //                highlight.userInfo = @{kWBLinkTopicName : topic};
    //                [text setTextHighlight:highlight range:range];
    //            }
    //            searchRange.location = searchRange.location + (searchRange.length ? searchRange.length : 1);
    //            if (searchRange.location + 1>= text.length) break;
    //            searchRange.length = text.length - searchRange.location;
    //        } while (1);
    //    }
    
    
    // 匹配 [表情]
    NSArray<NSTextCheckingResult *> *emoticonResults = [[BDPostHelper regexEmoticon] matchesInString:text.string options:kNilOptions range:text.rangeOfAll];
    NSUInteger emoClipLength = 0;
    for (NSTextCheckingResult *emo in emoticonResults) {
        if (emo.range.location == NSNotFound && emo.range.length <= 1) continue;
        NSRange range = emo.range;
        range.location -= emoClipLength;
        if ([text attribute:YYTextHighlightAttributeName atIndex:range.location]) continue;
        if ([text attribute:YYTextAttachmentAttributeName atIndex:range.location]) continue;
        NSString *emoString = [text.string substringWithRange:range];
        NSString *imageName = [BDPostHelper emoticonDic][emoString][@"gif"];
        
        UIImage *image = [BDPostHelper imageNamed:imageName];
        if (!image) continue;
        
        NSAttributedString *emoText = [NSAttributedString attachmentStringWithEmojiImage:image fontSize:fontSize];
        [text replaceCharactersInRange:range withAttributedString:emoText];
        emoClipLength += range.length - 1;
    }
    return text;
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
